#include "head.h"

// 数据操作
//  向文件写入航班信息
void flight_data_file_print(f_list *list)
{
    // 安全判断
    if (NULL == list)
    {
        ERRLOG("双向循环链表 为 NULL");
        return;
    }
    if (NULL == list->next)
    {
        ERRLOG("双向循环链表 为 NULL");
        return;
    }

    FILE *fp = fopen(FLIGHTS_FILE, "w+");
    if (NULL == fp)
    {
        ERRLOG("文件创建失败");
        return;
    }
    fseek(fp, 0, SEEK_SET);

    f_node *ptr = list->next;
    do
    {
        fprintf(fp, "%d\t", ptr->data.id);
        fprintf(fp, "%s\t", ptr->data.flighttype);
        fprintf(fp, "%s\t", ptr->data.startcity);
        fprintf(fp, "%s\t", ptr->data.arrivecity);
        fprintf(fp, "%d:%d\t", ptr->data.starttime[0], ptr->data.starttime[1]);
        fprintf(fp, "%d:%d\t", ptr->data.arrivetime[0], ptr->data.arrivetime[1]);
        fprintf(fp, "%s\t", ptr->data.flytime);
        fprintf(fp, "%d\t", ptr->data.value);
        fprintf(fp, "%d\t", ptr->data.maxNUM);
        fprintf(fp, "%d\t", ptr->data.leftbuyersa);
        fprintf(fp, "%c\n", ptr->data.whetherfly);
        ptr = ptr->next;
    } while (ptr != list->next);

    fflush(fp); // 刷新文件

    fclose(fp);
}
//  向文件读取航班信息
void flight_data_file_scanf(f_list *list)
{
    // 安全判断
    if (NULL == list)
    {
        ERRLOG("双向循环链表 为 NULL");
        return;
    }

    FILE *fp = fopen(FLIGHTS_FILE, "r+");
    if (NULL == fp)
    {
        ERRLOG("文件创建失败");
        return;
    }
    // 移动光标
    fseek(fp, 0, SEEK_SET);
    // 清空链表
    clear_double_link_list(list);
    //f_node *ptr = list->next;
    f_data data;
    char ch = 0;
    int pos = 0;

    // 检测文件行数
    while(EOF != (ch = fgetc(fp)))
    {
        if ('\n' ==  ch)
        {
            pos++;
        }
    }

    fflush(fp); // 刷新文件

    // 移动光标
    fseek(fp, 0, SEEK_SET);

    for (size_t i = 0; i < pos; i++)
    {
        fscanf(fp, "%d\t", &data.id);
        fscanf(fp, "%s\t", data.flighttype);
        fscanf(fp, "%s\t", data.startcity);
        fscanf(fp, "%s\t", data.arrivecity);
        fscanf(fp, "%d:%d\t", &data.starttime[0], &data.starttime[1]);
        fscanf(fp, "%d:%d\t", &data.arrivetime[0], &data.arrivetime[1]);
        fscanf(fp, "%s\t", data.flytime);
        fscanf(fp, "%d\t", &data.value);
        fscanf(fp, "%d\t", &data.maxNUM);
        fscanf(fp, "%d\t", &data.leftbuyersa);
        fscanf(fp, "%c\n", &data.whetherfly);

        insert_double_node(list, data, i + 1);
    }
    
    fflush(fp); // 刷新文件

    fclose(fp);
}